import json
from copy import deepcopy
from flask import Blueprint, request, jsonify
from controllers.common import *
from controllers.db import *

lucky_purchase_api = Blueprint('lucky_purchase_api', __name__)
lucky_purchase_down_api = Blueprint('lucky_purchase_down_api', __name__)
lucky_purchase_reward_pool_api = Blueprint('lucky_purchase_reward_pool_api', __name__)


@lucky_purchase_api.route('/lucky_purchase', methods=['POST'])
def lucky_purchase():
    params = json.loads(request.data)
    _action = params['action']
    _project = params['project']
    result_data = {'status': 200, 'data': {'msg': '', 'ret': 0, 'type': 'success', 'env': EVN, 'item': ''}}
    if _action == 'detail':
        query = LuckyPurchase.query.filter_by(project=_project).first()
        tmp = {
            "project": int(query.project),
            'basic': json.loads(query.basic),
            'detail': json.loads(query.detail)
        }
        result_data['data']['item'] = tmp
    elif _action == 'update_part':
        _data = params['data']
        _part = params['part']
        '''lucky_purchase_data = LuckyPurchase.query.filter_by(project=_project).first()
        reward = json.loads(lucky_purchase_data.reward)'''
        if _part == 'basic':
            LuckyPurchase.query.filter_by(project=_project).update({
                'basic': json.dumps(_data)
            })
        elif _part == 'detail':
            LuckyPurchase.query.filter_by(project=_project).update({
                'detail': json.dumps(_data)
            })
        db.session.commit()
        result_data['data']['msg'] = "更新成功"
    elif _action == 'iap_list':
        with open(STATIC_PATH + 'iap_list.json') as f:
            data = json.load(f)
            for i in data:
                i['value'] = i['gem']
                i['label'] = i['label'] + ' - ' + str(i['gem'])
            return json.dumps(data)
    elif _action == 'get_doc_id_list':
        return jsonify(get_doc_id_list_in_operation_event_english('lucky_purchase_event', 'title'))
    elif _action == 'get_reward_pool_list':
        result = []
        query_data = LuckyPurchaseRewardPool.query.filter_by(type='master').first()
        reward_pool_list = json.loads(query_data.data)['pool']
        for i in reward_pool_list:
            if i['remark'] == '':
                name = f"{i['id']}"
            else:
                name = f"{i['id']} - {i['remark']}"
            result.append({
                'value': i['id'],
                'label': name,
                'data': i
            })
        return jsonify(result)
    return jsonify(result_data)


@lucky_purchase_reward_pool_api.route('/lucky_purchase_reward_pool', methods=['POST'])
def lucky_purchase_reward_pool():
    params = json.loads(request.data)
    _action = params['action']
    result_data = {'status': 'status'}
    if _action == 'get_reward_pool':
        query_data = LuckyPurchaseRewardPool.query.filter_by(type='master').first()
        result = json.loads(query_data.data)
        result_data['data'] = result
    elif _action == 'save_reward_pool':
        query_data = LuckyPurchaseRewardPool.query.filter_by(type='master').first()
        query_data.data = json.dumps(params['data'])
        db.session.commit()

    return jsonify(result_data)


@lucky_purchase_down_api.route('/lucky_purchase_down/<int:is_push>/<int:file_index>', methods=['GET', 'POST'])
def lucky_purchase_down(is_push, file_index):
    lucky_purchase_event_project = {}
    lucky_purchase_random_reward_project = {}

    query = LuckyPurchase.query.order_by('project').all()
    reward_pool_query = LuckyPurchaseRewardPool.query.filter_by(type='master').first()
    reward_pool_data = json.loads(reward_pool_query.data)
    reward_pool_list = {}
    for i in reward_pool_data['pool']:
        reward_pool_list[str(i['id'])] = i

    for q in query:
        _project = str(q.project)
        basic = json.loads(q.basic)
        detail = json.loads(q.detail)

        purchase_list = []
        for i in detail['gift']:
            purchase_list.append({
                'reward': RewardToTMysqlNew(i['reward']),
                'limit_num': i['limit_num'],
                'basic_gems': i['basic_gems'],
                'random_reward_pool_id': i['random_reward_pool_id'],
                'scoring_rules': [1, 1, 1, 0],
                'package_id': i['id'],
                'project_id': int(f"1128{_project.zfill(4)}{str(i['id']).zfill(4)}")
            })
        lucky_purchase_event_project[_project] = {
            'basic_data': {
                'event_ui': basic['event_ui']
            },
            'doc_id': basic['doc_id'],
            'purchase_list': purchase_list
        }

    for pool_id in reward_pool_list:
        reward_pool = []
        for i in reward_pool_list[pool_id]['reward_best']:
            reward_pool.append({
                'sort': i['weight'],
                'reward': {
                    'a': [i['type'], i['id'], i['num']]
                },
                'reward_lv': 2
            })
        for i in reward_pool_list[pool_id]['reward_rare']:
            reward_pool.append({
                'sort': i['weight'],
                'reward': {
                    'a': [i['type'], i['id'], i['num']]
                },
                'reward_lv': 1
            })
        for i in reward_pool_list[pool_id]['reward_normal']:
            reward_pool.append({
                'sort': i['weight'],
                'reward': {
                    'a': [i['type'], i['id'], i['num']]
                },
                'reward_lv': 0
            })
        lucky_purchase_random_reward_project[pool_id] = {
            'reward_pool': reward_pool,
            'bottom_line': [reward_pool_list[pool_id]['bottom_line_best'] + 1, reward_pool_list[pool_id]['bottom_line_rare'] + 1]
        }

    if is_push == 0:
        if file_index == 0:
            response = DownLoad('lucky_purchase_event_project', lucky_purchase_event_project, 0)
        else:
            response = DownLoad('lucky_purchase_random_reward_project', lucky_purchase_random_reward_project, 0)
        return response
    else:
        response0 = DownLoad('lucky_purchase_event_project', lucky_purchase_event_project, 1)
        response1 = DownLoad('lucky_purchase_random_reward_project', lucky_purchase_random_reward_project, 1)
        return response1
